package com.example.sunran.resource;

import com.example.sunran.auth.TokenCodeUtils;
import com.example.sunran.auth.TokenNeeded;
import com.example.sunran.bean.User;
import com.example.sunran.service.LoginService;
import com.example.sunran.service.impl.LoginServiceImpl;
import org.apache.commons.codec.binary.Base64;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Path("api/login")
public class Login {
    private static LoginService loginService = new LoginServiceImpl();
    private static Random random = new Random();

    @GET
    @TokenNeeded
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String, Object> hello(@HeaderParam("sid")String sid){
        //能进入函数说明通过了filter
        Map<String,Object> map = new HashMap<>();
        User user = TokenCodeUtils.getUserInfo(sid);
        map.put("data",user);
        map.put("state","success");
        return map;
    }

    @POST
    public Response login(@FormParam("user")String user, @FormParam("pwd")String pwd) throws IOException, URISyntaxException {
        User userBean = loginService.login(user, pwd);

        Response response=null ;
        //登录成功设置返回token
        if (!userBean.getUser().equals("")) {
            String token = TokenCodeUtils.generator(String.valueOf(random.nextInt(99999)),userBean);
            String sid = "Bearer "+token;
            response = Response.status(302)
                                .cookie(new NewCookie("sid", Base64.encodeBase64String(sid.getBytes())))
                                .location(new URI("api/login"))
                                .build();
        }else{
            response = Response.status(200)
                        .build();
        }
        return response;
    }

}
